package wordPattern;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    public boolean wordPattern(String pattern, String s) {
        // 判断规律是否一致就是判断单词出现的位置是否一样
        Map<Character,String> map = new HashMap<>();
        List<String> words = help(s);
        if(words.size()!=pattern.length())return false;
        for (int i = 0; i < pattern.length(); i++) {
            // 得到s中的每个单词
            char c = pattern.charAt(i);
            String w = words.get(i);
            if(!map.containsKey(c)) {
                if(map.containsValue(w)) {
                   return false;
                }
                map.put(c,w);
            }
            else {
                if(!map.get(c).equals(w)) {
                    return false;
                }
            }
        }
        return true;
    }
    private List<String> help(String s) {
        List<String> words = new ArrayList<>();
        int i = 0;
        for (int j = 0; j < s.length(); j++) {
            if(s.charAt(j) == ' ') {
                words.add(s.substring(i,j));
                i = j+1;
            }
        }
        words.add(s.substring(i,s.length()));
        return words;
    }
}
